import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { authApi } from '@/api/auth'
import type { User, LoginData, RegisterData } from '@/types/auth'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const user = ref<User | null>(null)
  const token = ref<string | null>(localStorage.getItem('token'))
  const loading = ref(false)
  const avatarTimestamp = ref(Date.now()) // 用于强制刷新头像
  
  // 计算属性：用户已认证
  const isAuthenticated = computed(() => !!token.value && !!user.value)

  // 设置token
  const setToken = (newToken: string | null) => {
    token.value = newToken
    if (newToken) {
      localStorage.setItem('token', newToken)
    } else {
      localStorage.removeItem('token')
    }
  }

  // 设置用户信息
  const setUser = (newUser: User | null) => {
    // 检查头像是否变化
    if (newUser && user.value && newUser.avatar !== user.value.avatar) {
      avatarTimestamp.value = Date.now()
    }
    user.value = newUser
  }

  // 更新用户信息
  const updateUserInfo = (updates: Partial<User>) => {
    if (user.value) {
      user.value = { ...user.value, ...updates }
      // 如果更新了头像，更新时间戳
      if (updates.avatar) {
        avatarTimestamp.value = Date.now()
      }
    }
  }

  // 登录
  const login = async (loginData: LoginData) => {
    loading.value = true
    try {
      const response = await authApi.login(loginData)
      if (response.success && response.data) {
        setToken(response.data.accessToken)
        setUser(response.data.user)
        return response.data
      } else {
        throw new Error(response.message || '登录失败')
      }
    } finally {
      loading.value = false
    }
  }

  // 注册
  const register = async (registerData: RegisterData) => {
    loading.value = true
    try {
      const response = await authApi.register(registerData)
      if (response.success) {
        return response.data
      } else {
        throw new Error(response.message || '注册失败')
      }
    } finally {
      loading.value = false
    }
  }

  // 退出登录
  const logout = async () => {
    try {
      await authApi.logout()
    } catch (error) {
      console.error('Logout error:', error)
    } finally {
      setToken(null)
      setUser(null)
    }
  }

  // 获取当前用户信息
  const fetchCurrentUser = async () => {
    if (!token.value) return
    
    loading.value = true
    try {
      const response = await authApi.getCurrentUser()
      if (response.success && response.data) {
        setUser(response.data)
      } else {
        // Token无效，清除认证状态
        setToken(null)
        setUser(null)
      }
    } catch (error) {
      console.error('Fetch user error:', error)
      setToken(null)
      setUser(null)
    } finally {
      loading.value = false
    }
  }

  // 忘记密码
  const forgotPassword = async (email: string) => {
    loading.value = true
    try {
      const response = await authApi.forgotPassword(email)
      if (response.success) {
        return response.data
      } else {
        throw new Error(response.message || '发送重置邮件失败')
      }
    } finally {
      loading.value = false
    }
  }

  // 重置密码
  const resetPassword = async (token: string, password: string) => {
    loading.value = true
    try {
      const response = await authApi.resetPassword(token, password)
      if (response.success) {
        return response.data
      } else {
        throw new Error(response.message || '重置密码失败')
      }
    } finally {
      loading.value = false
    }
  }

  return {
    // 状态
    user,
    token,
    isAuthenticated,
    loading,
    avatarTimestamp,
    
    // 方法
    login,
    register,
    logout,
    fetchCurrentUser,
    forgotPassword,
    resetPassword,
    setToken,
    setUser,
    updateUserInfo
  }
})